<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
         <script>
            var dataView;
            var grid;
            var grid_opts={};
            var data = [];
            var selectedRowIds = [];

            var storyTitleFormatter = function(row, cell, value, columnDef, dataContext) {
                return "<a href='#jqtransform.jsp?" + dataContext["title"] + "' target=_self>" + dataContext["title"] + "</a>";
            };
            
            
            var columns = [
			
                {id:"title", name:"Title", field:"title", minWidth:100, cssClass:"cell-title", editor:TextCellEditor, validator:requiredFieldValidator, sortable:true, formatter:storyTitleFormatter },
                {id:"duration", name:"Duration", field:"duration", minWidth:100, editor:TextCellEditor, sortable:true},
                {id:"%", name:"% Complete", field:"percentComplete", width:150, resizable:false, formatter:GraphicalPercentCompleteCellFormatter, editor:PercentCompleteCellEditor, sortable:true},
                {id:"start", name:"Start", field:"start", minWidth:100, editor:DateCellEditor, sortable:true},
                {id:"finish", name:"Finish", field:"finish", minWidth:100, editor:DateCellEditor, sortable:true},
                {id:"effort-driven", name:"Effort Driven", width:110, resizable:false, cssClass:"cell-effort-driven", field:"effortDriven", formatter:BoolCellFormatter, editor:YesNoCheckboxCellEditor, cannotTriggerInsert:true, sortable:true}
            ];

            var options = {
                editable: false,
                autoEdit: false,
                enableAddRow: false,
                enableCellNavigation: true,
                asyncEditorLoading: false,
                enableColumnReorder: false,
                forceFitColumns: true
                        
            };

            var sortcol = "title";
            var sortdir = 1;
            var percentCompleteThreshold = 0;
            var searchString = "";

            function requiredFieldValidator(value) {
                if (value == null || value == undefined || !value.length)
                    return {valid:false, msg:"This is a required field"};
                else
                    return {valid:true, msg:null};
            }

            function myFilter(item) {
                if (item["percentComplete"] < percentCompleteThreshold)
                    return false;
         
                if (searchString != "" && item["title"].toLowerCase().indexOf(searchString.toLowerCase())==-1 && item["duration"].toLowerCase().indexOf(searchString.toLowerCase())==-1)
                    return false;

                return true;
            }

            function percentCompleteSort(a,b) {
                return a["percentComplete"] - b["percentComplete"];
            }

            function comparer(a,b) {
                var x = a[sortcol], y = b[sortcol];
                return (x == y ? 0 : (x > y ? 1 : -1));
            }

            function addItem(newItem,columnDef) {
                var item = {"num": data.length, "id": "new_" + (Math.round(Math.random()*10000)), "title":"New task", "duration":"1 day", "percentComplete":0, "start":"01/01/2009", "finish":"01/01/2009", "effortDriven":false};
                $.extend(item,newItem);
                dataView.addItem(item);
            }
            
            
            



        

            $(".grid-header .ui-icon")
            .addClass("ui-state-default ui-corner-all")
            .mouseover(function(e) {
                $(e.target).addClass("ui-state-hover")
            })
            .mouseout(function(e) {
                $(e.target).removeClass("ui-state-hover")
            });


            
            $(function()
            {
                // prepare the data
                for (var i=0; i<100; i++) {
                    var d = (data[i] = {});

                    d["id"] = "id_" + i;
                    d["num"] = i;
                    d["title"] = "Task " + i;
                    d["duration"] = (i%6==0 ? "5 days" : "8 days");
                    d["percentComplete"] = Math.round(Math.random() * 100);
                    d["start"] = "01/01/2009";
                    d["finish"] = "01/05/2009";
                    d["effortDriven"] = (i % 5 == 0);
                                
                }


                dataView = new Slick.Data.DataView();
                grid = new Slick.Grid($("#myGrid"), dataView.rows, columns, options);
                var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
                var columnpicker = new Slick.Controls.ColumnPicker(columns, grid, options);
                
                
                
                $.subscribe("set_grid_height", function (new_height) {
                    grid_opts.height = new_height;
                    $("#myGrid").css('height', grid_opts.height - 27);
                    grid.resizeCanvas();
                    jjmen();
                });
            
                $.subscribe("set_grid_width", function (new_width) {
                    grid_opts.width = new_width;
                    $("#myGrid").css('width', grid_opts.width );
                    $("#pager").css('width', grid_opts.width  );
                    grid.autosizeColumns();
                    jjmen();
                });


            

                /*   al cambiar el contenido de una celda
                 *   grid.onCellChange = function(row,col,item) {
              dataView.updateItem(item.id,item);    
          };

                      grid.onAddNewRow = addItem;
                 */  //al presionar teclas
                grid.onKeyDown = function(e) {
                    // select all rows on ctrl-a
                    if (e.which != 65 || !e.ctrlKey)
                    {
                        return false;
                    }  

                    var rows = [];
                    selectedRowIds = [];

                    for (var i = 0; i < dataView.rows.length; i++) {
                        rows.push(i);
                        selectedRowIds.push(dataView.rows[i].id);
                    }

                    grid.setSelectedRows(rows);

                    return true;
                };

                grid.onSelectedRowsChanged = function() {
               
                    selectedRowIds = [];
                    var rows = grid.getSelectedRows();
                    for (var i = 0, l = rows.length; i < l; i++) {
                        var item = dataView.rows[rows[i]];
                        if (item) selectedRowIds.push(item.id);
                    }
                };

		
                
                grid.onSort = function(sortCol, sortAsc) {
                    sortdir = sortAsc ? 1 : -1;
                    sortcol = sortCol.field;

                    // using native sort with comparer
                    // preferred method but can be very slow in IE with huge datasets
                    //dataView.sort(comparer,sortAsc);

                    // using temporary Object.prototype.toString override
                    // more limited and does lexicographic sort only by default, but can be much faster

                    var percentCompleteValueFn = function() {
                        var val = this["percentComplete"];
                        if (val < 10)
                            return "00" + val;
                        else if (val < 100)
                            return "0" + val;
                        else
                            return val;
                    };

                    // use numeric sort of % and lexicographic for everything else
                    dataView.fastSort((sortcol=="percentComplete")?percentCompleteValueFn:sortcol,sortAsc);
                
                    jjmen(); 
                
		
                
                
                };

                // wire up model events to drive the grid
                dataView.onRowCountChanged.subscribe(function(args) {
                    grid.updateRowCount();
                    grid.render();
                });

                dataView.onRowsChanged.subscribe(function(rows) {
                    grid.removeRows(rows);
                    grid.render();

                    if (selectedRowIds.length > 0)
                    {
                        // since how the original data maps onto rows has changed,
                        // the selected rows in the grid need to be updated
                        var selRows = [];
                        for (var i = 0; i < selectedRowIds.length; i++)
                        {
                            var idx = dataView.getRowById(selectedRowIds[i]);
                            if (idx != undefined)
                                selRows.push(idx);
                        }

                        grid.setSelectedRows(selRows);
                    }
                });

                dataView.onPagingInfoChanged.subscribe(function(pagingInfo) {
		    
                    grid.setOptions({enableAddRow:options.enableAddRow});
                });
                
                
                $("#txtSearch").keyup(function(e) {
                    Slick.GlobalEditorLock.cancelCurrentEdit();

                    // clear on Esc
                    if (e.which == 27)
                        this.value = "";

                    searchString = this.value;
                    dataView.refresh();
                });


                dataView.beginUpdate();
                dataView.setItems(data);
                dataView.setFilter(myFilter);
                dataView.endUpdate();
                        

                grid.onContextMenu = function (e, row, cell)
                {
                    if (!Slick.GlobalEditorLock.commitCurrentEdit()) { return; }
                            
                    if(selectedRowIds.length <= 1){
                        var rows = [];
                        selectedRowIds = [];
                        rows.push(row);
                        selectedRowIds.push("id_"+rows[0]);
                        grid.setSelectedRows(rows);
                    }

				
                

                    return true;
                };        

                $("#myGrid")
                .bind("draginit", function(e,dd) {
                    var cell = grid.getCellFromEvent(e);
                    if (!cell)
                        return false;

                    dd.row = cell.row;
                    if (!data[dd.row])
                        return false;

                    if (Slick.GlobalEditorLock.isActive() && !Slick.GlobalEditorLock.cancelCurrentEdit())
                        return false;
                });

                var jjmen = function() {
                      
                    $(".slick-row ").jjmenu("rightClick", 
                    // menu items:
                    [ {getByFunction:function(myData) {
                                return [{title:"eliminar: "+myData.tbRow()[0] },
                                    {title:"Duracion: "+myData.tbRow()[1] },
                                    {title:"%Complete: "+myData.tbRow()[2] },
                                    {title:"Start: "+myData.tbRow()[3] }
                                ];
                            }
                        } 
                    ], 
                    // myReplaces / userData:
                    {   "tbRow":function(){
                                            
                            var fila = jQuery(triggerElement);
                            var celdas = [];
                            jQuery(fila).children().each(function() {
                                celdas[celdas.length] = jQuery(this).html();
                                                                                       
                            });
                            if(selectedRowIds.length > 1){
                                celdas[0] ="seleccionados"; 
                            }
                            return celdas;    
                        }
                                          
                    }, 
                    // effects:
                    {show:"show", xposition:"mouse", yposition:"mouse"});
              
                };
                jjmen(); 
                  
                
            });
                
                

        </script>
    </head>
    <body>
        <div id="myGrid"></div>
        <div id="pager"></div>
    </body>
</html>
